package com.coda.interceptor;


import com.coda.context.BaseContext;
import com.coda.properties.JwtAdminProperties;
import com.coda.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtAdminProperties jwtAdminProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截的是Controller方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的方法不是动态方法直接放行
            return true;
        }

        try {
            //从请求头中获取令牌
            String token = request.getHeader(jwtAdminProperties.getAdminTokenName());

            //校验令牌
            log.info("后台管理校验令牌");
            Claims claims = JwtUtil.parseJWT(jwtAdminProperties.getAdminSecretKey(), token);
            Long id = Long.valueOf(claims.get("userId").toString());
            log.info("当前员工的id：{}", id);
            //获取员工id存入线程中
            BaseContext.setCurrentId(id);
            //放行
            return true;
        } catch (Exception e) {
            //不通过返回状态码
            response.setStatus(401);
            return false;
        }
    }

    /**
     * 清理用户信息
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }
}
